window.addEventListener('load', function () {
    let tbody = document.querySelector('tbody')
    //添加按钮
    let btnAddDialog = document.querySelector('.btnAddDialog')
    //表单
    let addForm = document.querySelector('.add-form')
    //确认添加按钮
    let btnAdd = document.querySelector('.btnAdd')
    // 姓名
    let name = document.querySelector('[name="name"]')
    // 年龄
    let age = document.querySelector('[name="age"]')
    // 组号
    let group = document.querySelector('[name="group"]')
    // 性别 :有两个元素，后期要根据数据为某一个添加checked
    let sexs = document.querySelectorAll('[name="sex"]')
    // 手机
    let phone = document.querySelector('[name="phone"]')
    // 期望薪资
    let salary = document.querySelector('[name="salary"]')
    // 实际薪资
    let truesalary = document.querySelector('[name="truesalary"]')
    //省
    let province = document.querySelector('[name=province]')
    //市
    let city = document.querySelector('[name=city]')
    //县
    let county = document.querySelector('[name=county]')
    //重置按钮
    let btnreset = document.querySelector('.btnreset')
    //模态框标题
    let addModalLabel = document.querySelector('#addModalLabel')
    // 遍历拼接渲染
    function init() {
        axios({
            method: 'get',
            url: '/student/list',
            // headers: { 'Authorization': localStorage.getItem('kshtoken') }
        }).then(res => {
            // console.log(res);
            let htmlStr = ''
            res.data.data.forEach((value, index) => {
                htmlStr += `<tr>
                                <th scope="row">${index + 1}</th>
                                <td>${value.name}</td>
                                <td>${value.age}</td>
                                <td>${value.sex}</td>
                                <td>${value.group}</td>
                                <td>${value.phone}</td>
                                <td>${value.salary}</td>
                                <td>${value.truesalary}</td>
                                <td>${value.province + value.city + value.county}</td>
                                <td>
                                  <button type="button" data-id=${value.id} class="btnEdit btn btn-primary btn-sm">修改</button>
                                  <button type="button" data-id=${value.id} class="btnDel btn btn-danger btn-sm">删除</button>
                                </td>
                            </tr>`
            })
            tbody.innerHTML = htmlStr
        })
    }
    init()
    //加载省的数据
    axios({
        method: 'get',
        url: '/geo/province',
    }).then(res => {
        // console.log(res);
        let htmlStr = `<option selected value="">--省--</option>`
        res.data.forEach(value => {
            htmlStr += `<option value="${value}">--${value}--</option>`
        })
        province.innerHTML = htmlStr
    })
    //加载市的数据,实现省市级连
    province.addEventListener('change', function () {
        city.innerHTML = '<option selected value="">--市--</option>'
        county.innerHTML = '<option selected value="">--县--</option>'
        let pname = province.value
        if (!pname) {
            return
        }
        axios({
            method: 'get',
            url: '/geo/city',
            params: { pname }
        }).then(res => {
            // console.log(res);
            let htmlStr = '<option selected value="">--市--</option>'
            res.data.forEach(value => {
                htmlStr += `<option value="${value}">--${value}--</option>`
            })
            city.innerHTML = htmlStr
        })
    })
    //加载县/区的数据,实现省市级连
    city.addEventListener('change', function () {
        county.innerHTML = '<option selected value="">--县--</option>'
        let pname = province.value
        let cname = city.value
        if (!cname) {
            return
        }
        axios({
            method: 'get',
            url: '/geo/county',
            params: { pname, cname }
        }).then(res => {
            // console.log(res);
            let htmlStr = '<option selected value="">--县--</option>'
            res.data.forEach(value => {
                htmlStr += `<option value="${value}">--${value}--</option>`
            })
            county.innerHTML = htmlStr
        })
    })

    //点击弹出添加模态框
    btnAddDialog.addEventListener('click', function () {
        $('#addModal').modal('show')
        //调用重置按钮清空表单数据
        btnreset.click()
        //修改标题
        addModalLabel.innerText = "录入新学员"
        //修改按钮的文本内容
        btnAdd.innerText = '确认添加'
    })
    //添加的表单验证
    function student() {
        return {
            fields: {
                name: {
                    validators: {
                        notEmpty: {
                            message: '姓名不能为空',
                        },
                        stringLength: {
                            min: 2,
                            max: 10,
                            message: '姓名长度2~10位'
                        }
                    }
                },
                age: {
                    validators: {
                        notEmpty: {
                            message: '年龄不能为空',
                        },
                        greaterThan: {
                            value: 18,
                            message: '年龄不能小于18岁'
                        },
                        lessThan: {
                            value: 60,
                            message: '年龄不能超过60岁'
                        }
                    }
                },
                sex: {
                    validators: {
                        choice: {
                            min: 1,
                            max: 1,
                            message: '请选择性别'
                        }
                    }
                },
                group: {
                    validators: {
                        notEmpty: {
                            message: '组号不能为空',
                        },
                        regexp: {
                            regexp: /^\d{1,2}$/,
                            message: '请选择有效的组号'
                        }
                    }
                },
                phone: {
                    validators: {
                        notEmpty: {
                            message: '手机号不能为空',
                        },
                        regexp: {
                            regexp: /^1\d{10}$/,
                            message: '请填写有效的手机号'
                        }
                    }
                },
                salary: {
                    validators: {
                        notEmpty: {
                            message: '实际薪资不能为空',
                        },
                        greaterThan: {
                            value: 800,
                            message: '期望薪资不能低于800'
                        },
                        lessThan: {
                            value: 99999,
                            message: '期望薪资不能高于100000'
                        }
                    }
                },
                truesalary: {
                    validators: {
                        notEmpty: {
                            message: '实际薪资不能为空',
                        },
                        greaterThan: {
                            value: 800,
                            message: '实际薪资不能低于800'
                        },
                        lessThan: {
                            value: 100000,
                            message: '实际薪资不能高于100000'
                        }
                    }
                },
                province: {
                    validators: {
                        notEmpty: {
                            message: '省份必填',
                        },
                    }
                },
                city: {
                    validators: {
                        notEmpty: {
                            message: '市必填',
                        },
                    }
                },
                county: {
                    validators: {
                        notEmpty: {
                            message: '县必填',
                        },
                    }
                },
            }
        }
    }
    let editId
    //实现添加功能
    $('.add-form').bootstrapValidator(student()).on('success.form.bv', function (e) {
        e.preventDefault();
        //使用formdata收集表单数据
        let formdata = new FormData(addForm)
        let data = {}
        formdata.forEach((value, key) => {
            // console.log(key, value);
            data[key] = value
        })

        if (addModalLabel == '录入新学员') {
            // console.log(data);
            axios({
                method: 'post',
                url: '/student/add',
                data,
            }).then(res => {
                // console.log(res);
                if (res.data.code == 0) {
                    toastr.success(res.data.message)
                } else {
                    toastr.warning(res.data.message)
                }
                $('#addModal').modal('hide')
                //调用重置按钮清空表单数据
                btnreset.click()
                init()
            })
            //调用编辑接口,实现编辑功能
        } else {
            data.id = editId
            axios({
                method: 'put',
                url: '/student/update',
                data
            }).then(res => {
                // console.log(res);
                if (res.data.code == 0) {
                    toastr.success(res.data.message)
                } else {
                    toastr.warning(res.data.message)
                }
                $('#addModal').modal('hide')
                init()
            })
        }
    })

    //实现删除功能
    tbody.addEventListener('click', function (e) {
        if (e.target.classList.contains('btnDel')) {
            if (confirm('确定是否删除')) {
                // console.log(123);
                axios({
                    method: 'delete',
                    url: '/student/delete',
                    params: { id: e.target.dataset.id }
                }).then(res => {
                    // console.log(res);
                    if (res.data.code == 0) {
                        toastr.success(res.data.message)
                    } else {
                        toastr.warning(res.data.message)
                    }
                    init()
                })
            }
        }
        //实现编辑功能
        if (e.target.classList.contains('btnEdit')) {
            // console.log(123);
            // 弹出模态框
            $('#addModal').modal('show')
            //修改标题
            addModalLabel.innerText = "编辑学员"
            //修改按钮的文本内容
            btnAdd.innerText = '确认编辑'
            // 获取当前数据的id
            let id = e.target.dataset.id
            editId = id
            // 根据id查询对应的数据
            axios({
                url: '/student/one',
                params: { id }
            }).then(res => {
                // console.log(res)
                let data = res.data.data
                // 常规表单元素，可以直接赋值value属性的
                name.value = data.name
                age.value = data.age
                phone.value = data.phone
                salary.value = data.salary
                truesalary.value = data.truesalary
                // 单选按钮
                data.sex == '男' ? (sexs[0].checked = true) : (sexs[1].checked = true)
                // 下拉列表
                group.value = data.group
                province.value = data.province
                // 如果没有value选项，也需要进行赋值，则可以设置它的innerHTML
                city.innerHTML = `<option selected value="${data.city}">--${data.city}--</option>`
                county.innerHTML = `<option selected value="${data.county}">--${data.county}--</option>`
                //触发省下拉列表的change事件--扩展
                let evt1 = document.createEvent('HTMLEvents')
                evt1.initEvent('change', false, false)
                province.dispatchEvent(evt1)
                setTimeout(() => {
                    city.value = data.city
                    let evt2 = document.createEvent('HTMLEvents')
                    evt2.initEvent('change', false, false)
                    city.dispatchEvent(evt2)
                    setTimeout(() => {
                        county.value = data.county
                    }, 1000)
                }, 1000)
            })
        }
    })
})